<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>远程数据库配置</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" />
    {% load custom_filters %}
  </head>
  <body>
    <div class="container mt-5">
      <h1 class="mb-4">远程数据库配置</h1>

      <!-- 配置表单 -->
      <div class="card mb-4">
        <div class="card-body">
          <form id="dbConfigForm">
            {% csrf_token %}
            <div class="row mb-3">
              <div class="col-md-6">
                <label for="{{ form.name.id_for_label }}" class="form-label">{{ form.name.label }}</label>
                {{ form.name|add_class:"form-control" }}
              </div>
              <div class="col-md-6">
                <label for="{{ form.engine.id_for_label }}" class="form-label">{{ form.engine.label }}</label>
                {{ form.engine|add_class:"form-select" }}
              </div>
            </div>

            <div class="row mb-3">
              <div class="col-md-6">
                <label for="{{ form.host.id_for_label }}" class="form-label">{{ form.host.label }}</label>
                {{ form.host|add_class:"form-control" }}
              </div>
              <div class="col-md-6">
                <label for="{{ form.port.id_for_label }}" class="form-label">{{ form.port.label }}</label>
                {{ form.port|add_class:"form-control" }}
              </div>
            </div>

            <div class="row mb-3">
              <div class="col-md-6">
                <label for="{{ form.database.id_for_label }}" class="form-label">{{ form.database.label }}</label>
                {{ form.database|add_class:"form-control" }}
              </div>
              <div class="col-md-6">
                <label for="{{ form.user.id_for_label }}" class="form-label">{{ form.user.label }}</label>
                {{ form.user|add_class:"form-control" }}
              </div>
            </div>

            <div class="mb-3">
              <label for="{{ form.password.id_for_label }}" class="form-label">{{ form.password.label }}</label>
              {{ form.password|add_class:"form-control" }}
            </div>

            <button type="button" id="testConnectionBtn" class="btn btn-primary">
              <i class="fa fa-plug"></i>
              测试连接
            </button>
          </form>
        </div>
      </div>

      <!-- 表和字段选择 -->
      <div id="tableSelectionSection" class="card mb-4 d-none">
        <div class="card-body">
          <h5 class="card-title">选择要暴露的表和字段</h5>
          <div id="tablesContainer" class="mt-3"></div>
          <button type="button" id="saveConfigBtn" class="btn btn-success mt-4">
            <i class="fa fa-save"></i>
            保存配置
          </button>
        </div>
      </div>

      <!-- 消息提示 -->
      <div id="messageAlert" class="alert d-none" role="alert"></div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      // 全局变量存储配置和表信息
      let currentConfig = null
      let tablesData = null

      // DOM元素
      const dbConfigForm = document.getElementById('dbConfigForm')
      const testConnectionBtn = document.getElementById('testConnectionBtn')
      const tableSelectionSection = document.getElementById('tableSelectionSection')
      const tablesContainer = document.getElementById('tablesContainer')
      const saveConfigBtn = document.getElementById('saveConfigBtn')
      const messageAlert = document.getElementById('messageAlert')

      // 测试连接按钮点击事件
      testConnectionBtn.addEventListener('click', async function () {
        showMessage('info', '正在测试连接...')
        const formData = new FormData(dbConfigForm)
        const formDataObject = Object.fromEntries(formData.entries())

        try {
          const response = await fetch('/test-connection/', {
            method: 'POST',
            headers: {
              'X-CSRFToken': formData.get('csrfmiddlewaretoken'),
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(formDataObject)
          })

          const result = await response.json()

          if (result.status === 'success') {
            showMessage('success', '连接成功！请选择要暴露的表和字段')
            currentConfig = result.config
            tablesData = result.tables
            renderTableSelection()
            tableSelectionSection.classList.remove('d-none')
          } else {
            showMessage('danger', `连接失败: ${result.message}`)
          }
        } catch (error) {
          showMessage('danger', `发生错误: ${error.message}`)
        }
      })

      // 渲染表和字段选择
      function renderTableSelection() {
        tablesContainer.innerHTML = ''

        tablesData.forEach((table) => {
          const tableDiv = document.createElement('div')
          tableDiv.className = 'mb-4'

          tableDiv.innerHTML = `
                    <div class="form-check">
                        <input class="form-check-input table-checkbox" type="checkbox" 
                               value="${table.name}" id="table_${table.name}">
                        <label class="form-check-label" for="table_${table.name}">
                            <strong>${table.name}</strong>
                        </label>
                    </div>
                    <div class="ms-4 fields-container d-none" data-table="${table.name}">
                        ${table.fields
                          .map(
                            (field) => `
                            <div class="form-check">
                                <input class="form-check-input field-checkbox" type="checkbox" 
                                       value="${field.name}" id="field_${table.name}_${field.name}"
                                       data-table="${table.name}">
                                <label class="form-check-label" for="field_${table.name}_${field.name}">
                                    ${field.name} (${field.type}${field.nullable ? ', 可为空' : ''})${field.description != '' ? '【' + field.description + '】' : ''}
                                </label>
                            </div>
                        `
                          )
                          .join('')}
                    </div>
                `

          tablesContainer.appendChild(tableDiv)
        })

        // 为表复选框添加事件监听
        document.querySelectorAll('.table-checkbox').forEach((checkbox) => {
          checkbox.addEventListener('change', function () {
            const tableName = this.value
            const fieldContainer = document.querySelector(`.fields-container[data-table="${tableName}"]`)
            const fieldCheckboxes = document.querySelectorAll(`.field-checkbox[data-table="${tableName}"]`)

            if (this.checked) {
              fieldContainer.classList.remove('d-none')
              fieldCheckboxes.forEach((fieldCheckbox) => {
                fieldCheckbox.checked = true
              })
            } else {
              fieldContainer.classList.add('d-none')
              fieldCheckboxes.forEach((fieldCheckbox) => {
                fieldCheckbox.checked = false
              })
            }
          })
        })
      }

      // 保存配置按钮点击事件
      saveConfigBtn.addEventListener('click', async function () {
        showMessage('info', '正在保存配置...')

        // 收集选中的表和字段
        const selectedTables = {}

        document.querySelectorAll('.table-checkbox:checked').forEach((tableCheckbox) => {
          const tableName = tableCheckbox.value
          const selectedFields = []

          document.querySelectorAll(`.field-checkbox[data-table="${tableName}"]:checked`).forEach((fieldCheckbox) => {
            selectedFields.push(fieldCheckbox.value)
          })

          if (selectedFields.length > 0) {
            selectedTables[tableName] = selectedFields
          }
        })

        if (Object.keys(selectedTables).length === 0) {
          showMessage('warning', '请至少选择一个表和字段')
          return
        }

        try {
          const response = await fetch('/save-config/', {
            method: 'POST',
            headers: {
              'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              config: currentConfig,
              selected_tables: selectedTables
            })
          })

          if (response.ok) {
            // 处理文件下载
            const blob = await response.blob()
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            
            // 从Content-Disposition头获取文件名
            const disposition = response.headers.get('Content-Disposition')
            let filename = 'config.json'
            if (disposition && disposition.includes('filename=')) {
              filename = disposition.split('filename=')[1].replace(/"/g, '')
            }
            a.download = filename
            
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(url)
            
            showMessage('success', '配置文件已下载')
          } else {
            const error = await response.json()
            showMessage('danger', `保存失败: ${error.message}`)
          }
        } catch (error) {
          showMessage('danger', `发生错误: ${error.message}`)
        }
      })

      // 显示消息提示
      function showMessage(type, text) {
        messageAlert.className = `alert alert-${type}`
        messageAlert.textContent = text
        messageAlert.classList.remove('d-none')

        // 5秒后自动隐藏
        setTimeout(() => {
          messageAlert.classList.add('d-none')
        }, 5000)
      }

      // 为表单字段添加类（Django表单渲染时使用）
      document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('input, select').forEach((element) => {
          if (!element.classList.contains('form-control') && !element.classList.contains('form-select') && !element.classList.contains('form-check-input')) {
            if (element.tagName === 'SELECT') {
              element.classList.add('form-select')
            } else {
              element.classList.add('form-control')
            }
          }
        })
      })
    </script>
  </body>
</html>
{% load custom_filters %}
